package com.flycat.controller;

import com.alibaba.fastjson.JSON;
import com.flycat.common.enumeration.MerchantTypeEnum;
import com.flycat.common.enumeration.StatusEnum;
import com.flycat.common.util.SessionUtils;
import com.flycat.core.Result;
import com.flycat.core.ResultGenerator;
import com.flycat.dao.po.MerchantInfo;
import com.flycat.dto.LoginDTO;
import com.flycat.service.MerchantInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Author yalei.chen
 * @Date 2017/10/17
 * @Since JDK 1.8
 */
@RestController
@Api(value = "登录",tags = "登录")
public class HomeController {

    private Logger logger = LoggerFactory.getLogger(HomeController.class);

    @Autowired
    private MerchantInfoService merchantInfoService;

    @PostMapping(value = "/loginSubmit")
    @ApiOperation(value = "登录")
    public Result<String> login(
            @RequestBody LoginDTO loginDTO,
            HttpSession session,
            HttpServletRequest request) {
        logger.info("登录的用户信息为，username:{},password:{}", loginDTO.getUsername(), loginDTO.getPassword());
        session.removeAttribute(SessionUtils.STORE_SESSION_USER);

        // 校验验证码是否正确
        String code = (String) session.getAttribute(SessionUtils.STORE_SESSION_CODE);

        MerchantInfo user = merchantInfoService.findBy("account", loginDTO.getUsername());

        if(Objects.isNull(user)){
            return ResultGenerator.genFailResult("error");
        }else {
            if(!loginDTO.getPassword().equals(user.getPassword()) ){
                return ResultGenerator.genFailResult("密码不正确");
            }

            if(StatusEnum.OFF_LINE.status == user.getStatus()){
                return ResultGenerator.genFailResult("该用户已下线，请于管理员联系");
            }
        }


        // 当用户密码校验通过后，将用户的信息放入到session中
        session.setAttribute(SessionUtils.STORE_SESSION_USER, user);
        logger.info("用户登录成功，用户信息为：{}", JSON.toJSONString(user));
        session.removeAttribute(SessionUtils.STORE_SESSION_CODE);    // 保证验证码一次有效性


        String preUrl   = (String)SessionUtils.getSession(request, SessionUtils.STORE_SESSION_PREURL);
        if(StringUtils.isNoneEmpty(preUrl) && !"/".equals(preUrl)){
            return ResultGenerator.genSuccessResult(preUrl);
        }

        if(user.getType() == MerchantTypeEnum.ADMIN.getCode()){

            return ResultGenerator.genSuccessResult("/admin");

        }else if(user.getType() == MerchantTypeEnum.SUPPLIER.getCode()){

            return ResultGenerator.genSuccessResult("/supplier");

        }else if(user.getType() == MerchantTypeEnum.DISTRIBUTOR.getCode()){

            return ResultGenerator.genSuccessResult("/distributor");
        }else {
            return ResultGenerator.genFailResult("用户类型不正确");
        }

    }

    @PostMapping("/logout")
    @ApiOperation(value = "登出")
    public Result<String> logout(HttpSession session) {
        MerchantInfo user = (MerchantInfo) session.getAttribute(SessionUtils.STORE_SESSION_USER);
        session.invalidate();
        logger.info("用户{},主动退出登录！", JSON.toJSONString(user));
        return ResultGenerator.genSuccessResult("用户退出登录成功");
    }
}
